require 'uri'
require 'net/http'
require 'rubygems'
require 'hpricot'
require 'htmlentities'
require 'cgi'
require 'iconv'
IRCBot::Plugin.define "michaelis" do
	help_string				"Checks the Michaelis portuguese dictionary."
	
	def command(user,target,message,usermask)
		if !message.empty? then
			res = Net::HTTP.get(URI.parse("http://michaelis.uol.com.br/moderno/portugues/index.php?lingua=portugues-portugues&palavra=#{URI.escape(message)}"))
			doc = Hpricot(res)
			
			if doc.at('div#tdcontents').at('label#contents').inner_html == "\nNenhuma palavra encontrada." then
				privmsg(target,"That word isn't in the dictionary.")
			else
				begin
					word = doc.at('div#tdcontents').at('span.palavraComPontos').inner_html
				rescue Exception
					word = message
				end
				word = Iconv.conv('ISO-8859-1','utf-8',HTMLEntities.new.decode(word))
				begin
					definition = doc.at('div#tdcontents').at('.descricao').inner_html
					definition = definition.gsub("<i>",0x1F.chr).gsub("</i>",0x1F.chr).gsub("<b>",2.chr).gsub("</b>",2.chr)
					definition = Iconv.conv('ISO-8859-1','utf-8',HTMLEntities.new.decode(definition))
				rescue Exception
					definition = "Something is wrong. D:"
				end
				
				privmsg(target,"#{0x1F.chr}#{word}#{0x1F.chr}: #{definition}")
			end
		end
	end
end
